#include "DefaultItemDelegate.h"
#include "../../KeySearchWidget.h"
#include <QJsonValue>
#include <QJsonArray>
#include <QPainter>

// #include <QJsonDocument>
// #include <QFile>
// #include <QDebug>

DefaultItemDelegate::DefaultItemDelegate(KeySearchWidget* parent)
	: QStyledItemDelegate(parent)
{
	
}

void DefaultItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	QVariant var = index.data(Qt::UserRole);
	QJsonArray data = var.toJsonArray();
	QRect rect = option.rect;

	//TODO: Tricky, 不设置listwidget的stylesheet，这里的MouseOver就不正常！
	if (option.state & QStyle::State_MouseOver && index.flags() !=  Qt::ItemFlag::NoItemFlags)
		painter->fillRect(rect, QColor(0x136C5E));				  
	
	QPen pen(QColor(0xFFEBC8));
	if (option.state.testFlag(QStyle::StateFlag::State_Selected))
		pen.setColor(QColor(0xFABF55));		//  
		
	painter->setPen(pen);
	
	for (int i = 1; i < data.size(); ++i)
	{
		if (i > m_widths.size())
			break;
					
		rect.setWidth(m_widths[i - 1]);
			
		if (data[i].toString() == "模块" || data[i].toString() == "债券") {
			pen.setColor(QColor(0xFABF55));
			painter->setPen(pen);	
		}

		painter->drawText(rect.adjusted(i==1?4:0,0,-5,0), Qt::AlignLeft | Qt::AlignVCenter, data[i].toString());
		rect.moveTo(rect.topRight());
		if (rect.left() > option.rect.right())
			break;
	}
}



QSize DefaultItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	return QSize(250, ITEM_DEFAULT_HEIGHT);
}
